package com.gjd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gjd.domain.entity.Admin;
import com.gjd.domain.entity.LoginAdmin;
import com.gjd.domain.entity.LoginUser;
import com.gjd.domain.entity.User;
import com.gjd.mapper.AdminMapper;
import com.gjd.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
// TODO: 2022/11/6 重写UserDetailsService方法，实现自己的用户校验
// TODO: 2023/2/6 根据用户选择的用户类型，匹配是家政人员还是雇主，如果不匹配，也不能登陆
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        根据用户名查询用户
        // TODO:此处导致了管理员和用户不能同名，设置两张数据库表的优势消失
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, username).eq(User::getUserType,"1");
        User user = userMapper.selectOne(wrapper);
//        根据名称查询管理员
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUserName, username).eq(Admin::getUserType,"0");
        Admin admin = adminMapper.selectOne(queryWrapper);

        if (Objects.nonNull(user)) {
            return new LoginUser(user, null);
        } else if (Objects.nonNull(admin)) {
            return new LoginAdmin(admin,null);
        }
        else {
            throw new RuntimeException("不存在");
        }
    }
}
